package com.buba.springboot.filemanager.controller;

import com.buba.springboot.congif.FilePropertiesConfig;
import com.buba.springboot.filemanager.dao.FileManagerMapper;
import com.buba.springboot.filemanager.service.FileManagerService;
import com.buba.springboot.pojo.user;
import com.buba.springboot.utils.CommonResult;
import com.buba.springboot.utils.FileUplode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/uploadFile")
@CrossOrigin
public class FileManagerController {
    @Autowired
    private FileManagerService fileManagerService;

    @Autowired
    private FileManagerMapper fileManagerMapper;

    @Autowired
    private FilePropertiesConfig filePropertiesConfig;

//导入
    @PostMapping("/uploadFiles")
    public void uploadFile(Integer id, HttpServletResponse response) {
        if (id != 0 && id != null) {
            //根据id查询文件信息
            FileUplode fileUplode = fileManagerMapper.selectQueryAll(id);
            //文件路径
            String fullPath = fileUplode.getFilePath();
            //创建输入流引用对象
            FileInputStream InputStream = null;
            //创建输出流引用对象
            ServletOutputStream servletOutputStream = null;
            //创建字节引用对象
            byte[] bytes = null;
            try {
                //创建输入流
                InputStream = new FileInputStream(fullPath);
                //获取字节长度
                int available = InputStream.available();
                //创建字节数组对象   获取输入流的字节长度
                bytes = new byte[available];
                //读取到输入流
                InputStream.read(bytes);
                //创建输出流
                servletOutputStream = response.getOutputStream();
                //设置响应类型
                response.setContentType("image/png;charset=utf-8");
                //写入到输出流
                servletOutputStream.write(bytes);
                //刷新
                servletOutputStream.flush();
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    InputStream.close();
                    servletOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

}
